import 'package:app/core/net/apis.dart';
import 'package:app/core/net/entity/base_entity.dart';
import 'package:app/core/net/request.dart';
import 'package:app/core/utils/helpers/sp.dart';
import 'package:app/routes/my_routes.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import 'entity/entity_login.dart';
import 'state.dart';

class LoginLogic extends GetxController {
  final state = LoginState();
  StorageController controller = Get.find<StorageController>();

  login(String name, String pwd) {
    // state.name.value = name;
    bool isValid = (name.length >= 6 && pwd.length >= 6) ? true : false;
    if (isValid) {
      _login(name, pwd);
    }
  }

  _login(String phone, String pwd) async {
    // Get.toNamed(RouteConfig.MAIN);

    var params = {"phone": phone, "pass": pwd};
    post(Apis.LOGIN_URL, params)
        .listen((event) {}, onDone: () {})
        .onData((data) {
      var bean = BaseEntity<LoginEntity>.fromJson(data);
      if (bean == null) {
        Fluttertoast.showToast(msg: "登录异常");
      } else {
        if (bean.code == 200) {
          // LogPrint.getInstance().printInfo("Login 成功 ${bean.data.token}");
          controller.setToken(bean.data.token);
          controller.setUserInfo(bean.data.toString());
          Get.toNamed(RouteConfig.MAIN);
        } else {
          Fluttertoast.showToast(msg: bean.msg);
        }
      }
    });
  }
}
